package com.cykj.pos.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.vo.BizMerchParentRelated;
import com.cykj.pos.domain.vo.StatisticVo;
import com.cykj.pos.service.*;
import com.cykj.system.domain.WalletNew;
import com.cykj.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import com.cykj.pos.mapper.BizWithdrawalRecordsMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 提现记录Service业务层处理
 *
 * @author weijianbo
 * @date 2025-02-12
 */
@Service
public class BizWithdrawalRecordsServiceImpl extends ServiceImpl<BizWithdrawalRecordsMapper, BizWithdrawalRecords> implements IBizWithdrawalRecordsService {


    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private IBizMerchantService iBizMerchantService;

    @Resource
    private IBizMicroInfoService iBizMicroInfoService;

    @Resource
    private BizWithdrawalRecordsMapper bizWithdrawalRecordsMapper;

    @Resource
    private IBizWalletNewService iBizWalletNewService;

    @Resource
    private IAizWithdrawalProfitService iAizWithdrawalProfitService;


    @Override
    public List<BizWithdrawalRecords> queryList(BizWithdrawalRecords bizWithdrawalRecords) {
        LambdaQueryWrapper<BizWithdrawalRecords> lqw = Wrappers.lambdaQuery();
        if (bizWithdrawalRecords.getChannelId() != null){
            lqw.eq(BizWithdrawalRecords::getChannelId ,bizWithdrawalRecords.getChannelId());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getChannelName())){
            lqw.like(BizWithdrawalRecords::getChannelName ,bizWithdrawalRecords.getChannelName());
        }
        if (bizWithdrawalRecords.getUserId() != null){
            lqw.eq(BizWithdrawalRecords::getUserId ,bizWithdrawalRecords.getUserId());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getUserName())){
            lqw.like(BizWithdrawalRecords::getUserName ,bizWithdrawalRecords.getUserName());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getMerchPhone())){
            lqw.eq(BizWithdrawalRecords::getMerchPhone ,bizWithdrawalRecords.getMerchPhone());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getWithdrawalName())){
            lqw.like(BizWithdrawalRecords::getWithdrawalName ,bizWithdrawalRecords.getWithdrawalName());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getWithdrawalAccount())){
            lqw.eq(BizWithdrawalRecords::getWithdrawalAccount ,bizWithdrawalRecords.getWithdrawalAccount());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getWithdrawalType())){
            lqw.eq(BizWithdrawalRecords::getWithdrawalType ,bizWithdrawalRecords.getWithdrawalType());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getPayStatus())){
            lqw.eq(BizWithdrawalRecords::getPayStatus ,bizWithdrawalRecords.getPayStatus());
        }
        if (bizWithdrawalRecords.getWithdrawalAmount() != null){
            lqw.eq(BizWithdrawalRecords::getWithdrawalAmount ,bizWithdrawalRecords.getWithdrawalAmount());
        }
        if (bizWithdrawalRecords.getArrivalAmount() != null){
            lqw.eq(BizWithdrawalRecords::getArrivalAmount ,bizWithdrawalRecords.getArrivalAmount());
        }
        if (bizWithdrawalRecords.getWalletAmount() != null){
            lqw.eq(BizWithdrawalRecords::getWalletAmount ,bizWithdrawalRecords.getWalletAmount());
        }
        if (bizWithdrawalRecords.getPayFee() != null){
            lqw.eq(BizWithdrawalRecords::getPayFee ,bizWithdrawalRecords.getPayFee());
        }
        if (bizWithdrawalRecords.getParams().get("beginTime") != null){
            lqw.ge(BizWithdrawalRecords::getWithdrawalTime ,bizWithdrawalRecords.getParams().get("beginTime")+" 00:00:00");
            lqw.le(BizWithdrawalRecords::getWithdrawalTime ,bizWithdrawalRecords.getParams().get("endTime")+" 23:59:59");
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getVar1())){
            lqw.eq(BizWithdrawalRecords::getVar1 ,bizWithdrawalRecords.getVar1());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getVar2())){
            lqw.eq(BizWithdrawalRecords::getVar2 ,bizWithdrawalRecords.getVar2());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getVar3())){
            lqw.eq(BizWithdrawalRecords::getVar3 ,bizWithdrawalRecords.getVar3());
        }
        if (StringUtils.isNotBlank(bizWithdrawalRecords.getRemark())){
            lqw.eq(BizWithdrawalRecords::getRemark ,bizWithdrawalRecords.getRemark());
        }
        if(bizWithdrawalRecords.getUserIds() != null){
            lqw.in(BizWithdrawalRecords::getUserId,bizWithdrawalRecords.getUserIds());
        }
        lqw.orderByAsc(BizWithdrawalRecords::getPayStatus);
        lqw.orderByDesc(BizWithdrawalRecords::getWithdrawalTime);
        return this.list(lqw);
    }

    @Override
    @Transactional
    public AjaxResult withdrawalZb(BizWalletNew bizWalletNewWithdrawal, BizWalletNew bizWalletData) {
        if("1".equals(bizWalletNewWithdrawal.getVar1())){
            if(bizWalletNewWithdrawal.getWithdrawalAmount().compareTo(bizWalletData.getProfitAmount()) > 0){
                return AjaxResult.error("分润账户余额不足,请重新输入");
            }
        }else{
            if(bizWalletNewWithdrawal.getWithdrawalAmount().compareTo(bizWalletData.getRewardAmount()) > 0){
                return AjaxResult.error("奖励账户余额不足,请重新输入");
            }
        }
        BizWithdrawalRecords bizWithdrawalRecords = new BizWithdrawalRecords();
        bizWithdrawalRecords.setChannelId(bizWalletData.getChannelId());
        bizWithdrawalRecords.setChannelName(bizWalletData.getChannelName());
        bizWithdrawalRecords.setUserId(bizWalletData.getUserId());
        SysUser user = iSysUserService.selectUserById(bizWalletData.getUserId());
        bizWithdrawalRecords.setMerchPhone(user.getPhonenumber());
        bizWithdrawalRecords.setUserName(user.getNickName());
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(bizWalletData.getUserId());
        BizMicroInfo bizMicroInfo = iBizMicroInfoService.getBizMicroInfoByMerchId(bizMerchant.getMerchId());
        bizWithdrawalRecords.setWithdrawalName(bizMicroInfo.getMerchIdcardName());
        bizWithdrawalRecords.setWithdrawalAccount(bizMicroInfo.getMerchBankCardno());
        bizWithdrawalRecords.setWithdrawalType(bizWalletNewWithdrawal.getVar1());//1 结算账户 2  奖励账户
        bizWithdrawalRecords.setWithdrawalAmount(bizWalletNewWithdrawal.getWithdrawalAmount());
        WithdrawalRateTemplate withdrawalRateTemplate = bizWithdrawalRecordsMapper.getDefaultWithdrawalRateTemplate();
        BigDecimal rate= BigDecimal.ZERO;
        BigDecimal fee = BigDecimal.ZERO;
        if("1".equals(bizWalletNewWithdrawal.getVar1())){
            rate = withdrawalRateTemplate.getProfitRate().subtract(bizMerchant.getWithdrawalRate());
            fee = withdrawalRateTemplate.getProfitFee().subtract(bizMerchant.getWithdrawalFee());
            bizWalletData.setProfitAmount(bizWalletData.getProfitAmount().subtract(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        }else{
            rate = withdrawalRateTemplate.getRewardRate().subtract(bizMerchant.getRewardWithdrawalRate());
            fee = withdrawalRateTemplate.getRewardFee().subtract(bizMerchant.getRewardWithdrawalFee());
            bizWalletData.setRewardAmount(bizWalletData.getRewardAmount().subtract(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        }
        bizWalletData.setWalletAmount(bizWalletData.getProfitAmount().add(bizWalletData.getRewardAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        // 手续费
        BigDecimal arrivalAmount = bizWalletNewWithdrawal.getWithdrawalAmount().multiply(rate).setScale(2,BigDecimal.ROUND_DOWN).add(fee);
        bizWithdrawalRecords.setPayFee(arrivalAmount);
        bizWithdrawalRecords.setArrivalAmount(bizWalletNewWithdrawal.getWithdrawalAmount().subtract(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
        bizWithdrawalRecords.setWalletAmount(bizWalletData.getWalletAmount());
        bizWithdrawalRecords.setWithdrawalTime(new Date());
        //处理钱包
        bizWalletData.setWithdrawalAmount(bizWalletData.getWithdrawalAmount().add(bizWalletNewWithdrawal.getWithdrawalAmount()).setScale(2,BigDecimal.ROUND_DOWN));
        bizWalletData.setWithdrawalServiceAmount(bizWalletData.getWithdrawalServiceAmount().add(arrivalAmount).setScale(2,BigDecimal.ROUND_DOWN));
        // 做关联   id
        String uuid = IdWorker.getIdStr();
        bizWithdrawalRecords.setVar2(uuid);
        bizWithdrawalRecords.setRemark(user.getDeptId() == 100L?"安心付-闯业" : user.getDeptId() == 101L?"安心付-伙伴":"安心付-乐富");
        if(this.saveOrUpdate(bizWithdrawalRecords)){ //保存记录
            iBizWalletNewService.saveOrUpdate(bizWalletData);//保存钱包
            return AjaxResult.success("提现申请已提交","true");
        }else{
            return AjaxResult.error("提现失败","false");
        }
    }

    public void executeMerchantWallet(BizWithdrawalRecords bizWithdrawalRecords){
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(bizWithdrawalRecords.getUserId());
        Long userId = bizMerchant.getUserId();// 提现代理
        String nickName = bizMerchant.getMerchName();// 提现代理
        // 查询全部上级
        List<BizMerchParentRelated> bizMerchParentRelatedList = iBizMerchantService.getMerchantListByMerchId(bizMerchant.getMerchId());
        for(BizMerchParentRelated related : bizMerchParentRelatedList){
            //父级
            BizMerchant bizMerchantParent = iBizMerchantService.getMerchantByMerchId(related.getParentId());
            //子级
            BizMerchant bizMerchantChild = iBizMerchantService.getMerchantByMerchId(bizMerchant.getMerchId());
            // 费率差  上级的费率  减去我的费率  是我的分润
            BigDecimal withdrawalRateParent = bizMerchantParent.getWithdrawalRate();//父级分润费率
            BigDecimal withdrawRateChild = bizMerchantChild.getWithdrawalRate();//子级分润费率
            if("2".equals(bizWithdrawalRecords.getWithdrawalType())){// 机具返现账户 则使用机具返现费率
                withdrawalRateParent = bizMerchantParent.getRewardWithdrawalRate();//父级机具返现费率
                withdrawRateChild = bizMerchantChild.getRewardWithdrawalRate();//子级机具返现费率
            }
            //提现分润  费率差
            BigDecimal finalRate= withdrawalRateParent.subtract(withdrawRateChild).setScale(2,BigDecimal.ROUND_DOWN);
            // 提现分润 金额
            BigDecimal finalRateProfit = bizWithdrawalRecords.getWithdrawalAmount().multiply(finalRate).setScale(2,BigDecimal.ROUND_DOWN);
            // 单笔差
            BigDecimal withdrawalFeeParent = bizMerchantParent.getWithdrawalFee();//父级分润返现单笔
            BigDecimal withdrawalFeeChild = bizMerchantChild.getWithdrawalFee();//子级分润返现单笔
            if("2".equals(bizWithdrawalRecords.getWithdrawalType())){
                withdrawalFeeParent = bizMerchantParent.getRewardWithdrawalFee();//父级奖励返现单笔
                withdrawalFeeChild = bizMerchantChild.getRewardWithdrawalFee();//子级奖励返现单笔
            }
            // 父级-子级的单笔
            BigDecimal finalFeeProfit = withdrawalFeeParent.subtract(withdrawalFeeChild).setScale(2,BigDecimal.ROUND_DOWN);
            // 最终分润
            BigDecimal finalProfit = finalRateProfit.add(finalFeeProfit);
            if(finalProfit.compareTo(BigDecimal.ZERO) > 0){
                // 保存至提现分润钱包
                AizWithdrawalWallet aizWithdrawalWallet =
                        iBizWalletNewService.getWithdrawalWalletByUserId(bizMerchantParent.getUserId(),bizWithdrawalRecords.getChannelId());
                if(aizWithdrawalWallet != null){
                    aizWithdrawalWallet.setAmount(aizWithdrawalWallet.getAmount().add(finalProfit));
                    aizWithdrawalWallet.setChannelId(bizWithdrawalRecords.getChannelId());
                    iBizWalletNewService.updateAizWithdrawalWalletByUserId(aizWithdrawalWallet);
                    SysUser sysUser = iSysUserService.selectUserById(bizMerchantParent.getUserId());
                    //提现分润记录
                    AizWithdrawalProfit aizWithdrawalProfit = new AizWithdrawalProfit();
                    aizWithdrawalProfit.setProfitUserId(sysUser.getUserId());
                    aizWithdrawalProfit.setProfitUserName(sysUser.getNickName());
                    aizWithdrawalProfit.setProfitRate(finalRate.doubleValue());
                    aizWithdrawalProfit.setProfitAmount(finalRateProfit.doubleValue());
                    aizWithdrawalProfit.setProfitFee(finalFeeProfit.doubleValue());
                    aizWithdrawalProfit.setWithdrawalUserId(userId);
                    aizWithdrawalProfit.setWithdrawalUserName(nickName);
                    aizWithdrawalProfit.setWithdrawalAmount(bizWithdrawalRecords.getWithdrawalAmount().doubleValue());
                    aizWithdrawalProfit.setWithdrawalRate(bizMerchant.getWithdrawalRate());
                    aizWithdrawalProfit.setCreateTime(new Date());
                    aizWithdrawalProfit.setVar1(bizWithdrawalRecords.getWithdrawalType());
                    aizWithdrawalProfit.setVar2(bizWithdrawalRecords.getVar2());
                    iAizWithdrawalProfitService.saveOrUpdate(aizWithdrawalProfit);
                }else{
                    System.out.println(bizMerchantParent.getUserId()+"未配置提现分润钱包,无法分润");
                }
            }
            // 处理上一级
            bizMerchant.setMerchId(bizMerchantParent.getMerchId());
            if(related.getParentId() == 2L){// 计算完服务中心结束
                break;
            }
        }
    }



    @Override
    public AjaxResult appBackRecords(BizWithdrawalRecords bizWithdrawalRecords) {
        bizWithdrawalRecords.setPageNo((bizWithdrawalRecords.getPageNo()-1)*bizWithdrawalRecords.getPageSize());
        List<BizWithdrawalRecords> listBack = bizWithdrawalRecordsMapper.appBackRecords(bizWithdrawalRecords);
        return AjaxResult.success("提现列表",listBack);
    }

    @Override
    public AjaxResult refundWithdrawal(BizWithdrawalRecords bizWithdrawalRecords) {
        String var3 = bizWithdrawalRecords.getVar3();
        // 钱包退回金额
        bizWithdrawalRecords = bizWithdrawalRecordsMapper.selectById(bizWithdrawalRecords.getId());
        System.out.println(bizWithdrawalRecords.getUserId()+"提现驳回"+bizWithdrawalRecords);
        if("3".equals(bizWithdrawalRecords.getWithdrawalType())){// 奖励钱包
            AizWithdrawalWallet aizWithdrawalWallet =
                    iBizWalletNewService.getWithdrawalWalletByUserIdAndChannelId(
                            bizWithdrawalRecords.getUserId(),bizWithdrawalRecords.getChannelId());
            aizWithdrawalWallet.setAmount(aizWithdrawalWallet.getAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
            iBizWalletNewService.updateAizWithdrawalWalletByUserId(aizWithdrawalWallet);
            System.out.println(bizWithdrawalRecords.getUserId()+"提现驳回至奖励钱包"+bizWithdrawalRecords.getWithdrawalAmount()+"元");
        }else{// 分润和返现钱包
            BizWalletNew bizWalletNew =
                    iBizWalletNewService.getWalletNewByUserIdAndChannel(
                            bizWithdrawalRecords.getUserId(),bizWithdrawalRecords.getChannelId());
            if("1".equals(bizWithdrawalRecords.getWithdrawalType())){// 分润钱包
                bizWalletNew.setProfitAmount(bizWalletNew.getProfitAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
            }else{// 返现钱包
                bizWalletNew.setRewardAmount(bizWalletNew.getRewardAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
            }
            bizWalletNew.setWalletAmount(bizWalletNew.getWalletAmount().add(bizWithdrawalRecords.getWithdrawalAmount()));
            iBizWalletNewService.saveOrUpdate(bizWalletNew);
            System.out.println(bizWithdrawalRecords.getUserId()+"提现驳回至分润返现钱包"+bizWithdrawalRecords.getWithdrawalAmount()+"元");
        }
        bizWithdrawalRecords.setVar3(var3);// 驳回原因
        bizWithdrawalRecords.setPayStatus("2");
        if(this.saveOrUpdate(bizWithdrawalRecords)){
            System.out.println(bizWithdrawalRecords.getUserId()+"提现驳回成功,更新状态成功");
            return AjaxResult.success("提现退回成功");
        }else{
            System.out.println(bizWithdrawalRecords.getUserId()+"提现驳回成功,更新状态失败");
            return AjaxResult.error("");
        }
    }

    @Override
    public AjaxResult executeGetStatistic(BizWithdrawalRecords bizWithdrawalRecords){
        AjaxResult ajaxResult = new AjaxResult();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(sysUser.getUserId() == 2L || sysUser.getUserId() == 1L){
            bizWithdrawalRecords.setRemark("安心付-闯业");
        }else if(sysUser.getUserId() == 23L){
            bizWithdrawalRecords.setRemark("安心付-伙伴");
        }else if(sysUser.getUserId() == 39L){
            bizWithdrawalRecords.setRemark("安心付-乐富");
        }
        ajaxResult.put("code",200);
        ajaxResult.put("msg","统计");
        if(bizWithdrawalRecords.getParams().get("beginTime") != null){
            bizWithdrawalRecords.setBeginTime(bizWithdrawalRecords.getParams().get("beginTime").toString()+" 00:00:00");
            bizWithdrawalRecords.setEndTime(bizWithdrawalRecords.getParams().get("endTime").toString()+" 23:59:59");
        }
        bizWithdrawalRecords.setPayStatus("0");
        ajaxResult.put("noPay",bizWithdrawalRecordsMapper.selectStatistic(bizWithdrawalRecords));
        bizWithdrawalRecords.setPayStatus("1");
        ajaxResult.put("paid",bizWithdrawalRecordsMapper.selectStatistic(bizWithdrawalRecords));
        bizWithdrawalRecords.setPayStatus("2");
        ajaxResult.put("rejected",bizWithdrawalRecordsMapper.selectStatistic(bizWithdrawalRecords));
        return ajaxResult;
    }

}
